{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import libraries that will help us preprocess data, map to word embeddings\n",
    "import torchtext\n",
    "from torchtext.vocab import Vectors, GloVe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# this will be our input x to the classifiers\n",
    "TEXT = torchtext.data.Field()\n",
    "\n",
    "# this will be what we map to, the tag y\n",
    "LABEL = torchtext.data.Field(sequential=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# split the dataset into train, val, and test sets. Exclude neutral labels, so just positive or negative\n",
    "train, val, test = torchtext.datasets.SST.splits(TEXT, LABEL, filter_pred=lambda ex: ex.label != 'neutral')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "len(train) 6920\n",
      "vars(train[0]) {'text': ['The', 'Rock', 'is', 'destined', 'to', 'be', 'the', '21st', 'Century', \"'s\", 'new', '``', 'Conan', \"''\", 'and', 'that', 'he', \"'s\", 'going', 'to', 'make', 'a', 'splash', 'even', 'greater', 'than', 'Arnold', 'Schwarzenegger', ',', 'Jean-Claud', 'Van', 'Damme', 'or', 'Steven', 'Segal', '.'], 'label': 'positive'}\n"
     ]
    }
   ],
   "source": [
    "# each consists of a label and it's original words\n",
    "print('len(train)', len(train))\n",
    "print('vars(train[0])', vars(train[0]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "len(TEXT.vocab) 16284\n",
      "len(LABEL.vocab) 3\n"
     ]
    }
   ],
   "source": [
    "# assign an index to each word and label (unique) kind of like countvectorizer\n",
    "TEXT.build_vocab(train)\n",
    "LABEL.build_vocab(train)\n",
    "print('len(TEXT.vocab)', len(TEXT.vocab))\n",
    "print('len(LABEL.vocab)', len(LABEL.vocab))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "# produce three batch iterators that iterate 10 examples at a time\n",
    "train_iter, val_iter, test_iter = torchtext.data.BucketIterator.splits((train, val, test), batch_size=10, device=-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Size of text batch [max sent length, batch size] torch.Size([31, 10])\n",
      "Second in batch Variable containing:\n",
      "   835\n",
      "     6\n",
      "    14\n",
      "  2490\n",
      "     5\n",
      "     4\n",
      "  2458\n",
      "     9\n",
      "    35\n",
      "   871\n",
      "     3\n",
      " 11218\n",
      "   219\n",
      "   180\n",
      "  1217\n",
      "     6\n",
      "     4\n",
      "   851\n",
      " 11645\n",
      "    15\n",
      "    88\n",
      "  4308\n",
      "   128\n",
      "     8\n",
      " 14154\n",
      "    15\n",
      "     4\n",
      "   196\n",
      " 12687\n",
      "     2\n",
      "     1\n",
      "[torch.LongTensor of size 31]\n",
      "\n",
      "Converted back to string:  Much of The Lady and the Duke is about quiet , decisive moments between members of the cultural elite as they determine how to proceed as the world implodes . <pad>\n"
     ]
    }
   ],
   "source": [
    "# consider a batch generated by one of these iterators. \n",
    "# Yields [max_sent_len, batch_size] and the indices in the 0th dim are the word IDs\n",
    "batch = next(iter(train_iter))\n",
    "print(\"Size of text batch [max sent length, batch size]\", batch.text.size())\n",
    "print(\"Second in batch\", batch.text[:, 0])\n",
    "print(\"Converted back to string: \", \" \".join([TEXT.vocab.itos[i] for i in batch.text[:, 0].data]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      ".vector_cache/wiki.simple.vec: 293MB [13:09, 398kB/s]                               \n",
      "  0%|          | 0/111052 [00:00<?, ?it/s]Skipping token 111051 with 1-dimensional vector ['300']; likely a header\n",
      "100%|██████████| 111052/111052 [00:12<00:00, 9224.36it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Word embeddings size  torch.Size([16284, 300])\n",
      "Word embedding of 'follows', first 10 dim  \n",
      " 0.3925\n",
      "-0.4770\n",
      " 0.1754\n",
      "-0.0845\n",
      " 0.1396\n",
      " 0.3722\n",
      "-0.0878\n",
      "-0.2398\n",
      " 0.0367\n",
      " 0.2800\n",
      "[torch.FloatTensor of size 10]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Build the vocabulary with word embeddings\n",
    "url = 'https://s3-us-west-1.amazonaws.com/fasttext-vectors/wiki.simple.vec'\n",
    "TEXT.vocab.load_vectors(vectors=Vectors('wiki.simple.vec', url=url))\n",
    "\n",
    "print(\"Word embeddings size \", TEXT.vocab.vectors.size())\n",
    "print(\"Word embedding of 'follows', first 10 dim \", TEXT.vocab.vectors[TEXT.vocab.stoi['follows']][:10])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
